package com.skylink.gaea.leaf.snowflake;

import com.skylink.gaea.leaf.IDGen;
import com.skylink.gaea.leaf.snowflake.exception.UidException;
import lombok.extern.slf4j.Slf4j;

/**
 * 单节点 ID 生成器，不可用于分布式场景。
 *
 * @author wangzezhou
 */
@Slf4j
public class StandaloneSnowflakeID implements IDGen {

    /**
     * 起始时间戳： 2023-03-20 09:00:00
     */
    private static final long EPOCH = 1679904484000L;
    private static final long WORKER_ID_BITES = 5L;
    private final long        SEQUENCE_BITS = 7L;

    // 最大能够分配的 workerid = 1^4
    private static final long MAX_WORKER_ID = ~(-1L<<WORKER_ID_BITES);
    private final long        workerIdShift      = SEQUENCE_BITS;
    private final long        timestampLeftShift = SEQUENCE_BITS + WORKER_ID_BITES;
    private final long        sequenceMask       = ~(-1L<<SEQUENCE_BITS);
    private long              workerId           = 0;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public StandaloneSnowflakeID() {
    }

    @Override
    public synchronized long nextId() {

        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            long offset = lastTimestamp - timestamp;
            if (offset <= 5) {
                try {
                    wait(offset << 1);
                    timestamp = timeGen();
                    if (timestamp < lastTimestamp) {
                        throw new UidException("生成 ID 失败，当前时间({})大于最后生成时间戳({}),补偿偏移后时间依赖没有对齐",timestamp,lastTimestamp);
                    }
                } catch (InterruptedException e) {
                    log.error("wait interrupted");
                    throw new UidException("生成 ID 失败，补尝时间发生 Interrupted Exception");
                }
            } else {
                throw new UidException("生成 ID 失败，当前时间({})大于最后生成时间戳({})",timestamp,lastTimestamp);
            }
        }
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if( sequence == 0 ){
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            //如果是新的ms开始
            sequence = 0;
        }
        lastTimestamp = timestamp;
        return ((timestamp - EPOCH)<<timestampLeftShift)|(workerId<<workerIdShift)|sequence;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }

    public long getWorkerId() {
        return workerId;
    }
}
